﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Hydra.Shell.Interfaces;
using System.Diagnostics;

namespace Hydra.PackageFramework
{
    public static class UIHierarchyUtilities
    {
        /// <summary>
        /// Get reference to IHydraUIHierarchyWindow interface from guid persistence slot.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="persistenceSlot">Unique identifier for a tool window created using IHydraUIShell::CreateToolWindow. 
        /// The caller of this method can use predefined identifiers that map to tool windows if those tool windows 
        /// are known to the caller. </param>
        /// <returns>A reference to an IHydraUIHierarchyWindow interface.</returns>
        public static IHydraUIHierarchyWindow GetUIHierarchyWindow(Hydra.Shell.Interfaces.IServiceProvider serviceProvider, Guid persistenceSlot)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }

            IHydraUIShell shell = serviceProvider.GetService<IHydraUIShell>();

            Debug.Assert(shell != null, "Could not get the ui shell from the project");
            if (shell == null)
            {
                throw new InvalidOperationException();
            }

            object pvar = null;
            IHydraWindowFrame frame = null;
            IHydraUIHierarchyWindow uiHierarchyWindow = null;

            try
            {
                shell.FindToolWindow(0, ref persistenceSlot, out frame);
                frame.GetProperty(Shell.Enumerations.HydraFrameProperties.DocView, out pvar);
            }
            finally
            {
                if (pvar != null)
                {
                    uiHierarchyWindow = (IHydraUIHierarchyWindow)pvar;
                }
            }

            return uiHierarchyWindow;
        }
    }
}
